﻿using System;
using System.IO;

namespace movie.tool.module.http
{
    public class ChunkStream : Stream
    {
        private readonly Stream _baseStream;
        private readonly long _offset;
        private readonly long _length;
        private long _position;

        public ChunkStream(Stream baseStream, long offset, long length)
        {
            _baseStream = baseStream;
            _offset = offset;
            _length = length;
            _position = 0;
        }

        public override bool CanRead => true;
        public override bool CanSeek => false;
        public override bool CanWrite => false;
        public override long Length => _length;

        public override long Position
        {
            get => _position;
            set => throw new NotSupportedException();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            lock (_baseStream)
            {
                // 确保不会读取超出分片范围
                var bytesRemaining = _length - _position;
                if (bytesRemaining <= 0)
                    return 0;

                var bytesToRead = (int)Math.Min(count, bytesRemaining);

                // 定位到分片的正确位置
                _baseStream.Seek(_offset + _position, SeekOrigin.Begin);

                var bytesRead = _baseStream.Read(buffer, offset, bytesToRead);
                _position += bytesRead;

                return bytesRead;
            }
        }

        public override void Flush() => throw new NotSupportedException();
        public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
        public override void SetLength(long value) => throw new NotSupportedException();
        public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
    }
}
